<template>
  <a-modal :bodyStyle="{ padding: '0', 'max-height': '80vh', 'overflow-y': 'auto' }" :title="title" :width="1000" :maskClosable="false" :visible="visible" @cancel="visible = false" :button_loading="button_loading">
    <a slot="footer">
      <a-button @click="handleSubmit" type="primary" v-if="actionType != 'view'">保存</a-button>
      <a-button @click="visible = false">{{actionType == 'view' ? '关闭':'取消'}}</a-button>
    </a>

    <a-spin :indicator="indicator" :spinning="spinning" :tip="tip">
      <div class="spin-content" v-if="actionType != 'view'">

        <a-form :form="form">
          <a-row :gutter="16">
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="租赁联系人">
                <a-input placeholder="填写租赁联系人" v-decorator="[
                    'linkMan',
                    { rules: [{ required: true, message: '填写租赁联系人!' }] },
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="租赁联系人电话">
                <a-input placeholder="填写租赁联系人电话" v-decorator="[
                    'linkManTel',
                    { rules: [{ required: true, message: '填写租赁联系人电话!' }] },
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="证件类型">
                <a-select showSearch optionFilterProp="children" v-decorator="[
        'credentialsType',
    ]">
                  <a-select-option v-for="(item, index) in credentialsTypeList" :key="item.value" :value="item.value">{{
        item.label }}</a-select-option>
                </a-select>

              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="证件号码">
                <a-input placeholder="填写证件号码" v-decorator="[
                    'credentialsNo',
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="设施处置方式">
                <a-select showSearch optionFilterProp="children" v-decorator="[
        'disposalMethod_',
    ]">
                  <a-select-option v-for="(item, index) in disposalList" :key="item.value" :value="item.value">{{
        item.label }}</a-select-option>
                </a-select>

              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="租户类型">
                <a-select showSearch optionFilterProp="children" v-decorator="[
        'tenantType',
        { rules: [{ required: true, message: '请选择设施处置方式!' }] },
    ]">
                  <a-select-option v-for="(item, index) in tenantTypeList" :key="item.value" :value="item.value">{{
        item.label }}</a-select-option>
                </a-select>

              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="支付周期">
                <a-select showSearch optionFilterProp="children" v-decorator="[
        'rentPay',
        { rules: [{ required: true, message: '请选择支付周期!' }] },
    ]">
                  <a-select-option v-for="(item, index) in rentPayList" :key="item.value" :value="item.value">{{
        item.label }}</a-select-option>
                </a-select>

              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="是否签约合同">
                <a-select showSearch optionFilterProp="children" v-decorator="[
        'isSignContract',
        { rules: [{ required: true, message: '请选择是否签约合同!' }] },
    ]">
                  <a-select-option :value="1">是</a-select-option>
                  <a-select-option :value="0">否</a-select-option>
                </a-select>

              </a-form-item>
            </a-col>

            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="附属建筑和资产">
                <a-input placeholder="填写附属建筑和资产" v-decorator="[
                    'associatedAssets',
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="每平方米/元/年">
                <a-input placeholder="填写平方米/元/年产" v-decorator="[
                    'unitAmount',
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="合同月租金(元)">
                <a-input placeholder="填写金额" v-decorator="[
                    'rent',
                    { rules: [{ required: true, message: '填写金额!' }] },
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="押金(元)">
                <a-input placeholder="填写押金" v-decorator="[
                    'rentalDeposit',
                  ]" />
              </a-form-item>
            </a-col>
            <a-col class="gutter-row" :span="12">
              <a-form-item v-bind="formItemLayout1" label="合同面积(㎡)">
                <a-input placeholder="填写合同面积" v-decorator="[
                    'area',
                  ]" />
              </a-form-item>
            </a-col>

          </a-row>

          <a-form-item v-bind="formItemLayout2" label="选择关联房间">
            <a size="small" type="link" @click="handleChoose">选择房间</a>
            <!-- {{ roomNames }} -->
            <a-tag v-for="(item,index) in roomNames" :key="item.id" closable @close="CloseRoom(index)">
              {{item.name}}
            </a-tag>
          </a-form-item>

          <a-form-item v-bind="formItemLayout2" label="联系地址">
            <a-input placeholder="填写联系地址" v-decorator="[
                    'address',
                  ]" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout2" label="租赁日期">
            <a-range-picker :ranges="{
              一周内: [moment(), moment().endOf('week')],
              一月内: [moment(), moment().endOf('month')],
              一年内: [moment(), moment().endOf('year')],
            }" style="width: 100%" v-decorator="[
                    'date',
                   { rules: [{ required: true, message: '选中租赁日期!' }] },
                  ]" valueFormat="YYYY-MM-DD" />
          </a-form-item>
          <a-form-item v-bind="formItemLayout2" label="备注">
            <a-input placeholder="填写备注" v-decorator="[
                    'remark',
                  ]" />
          </a-form-item>
        </a-form>

      </div>

      <div class="spin-content" v-else>
        <a-descriptions :column="1">
          <a-descriptions-item label="租赁联系人">
            {{ objectInfo.linkMan }}
          </a-descriptions-item>
          <a-descriptions-item label="租赁联系人电话">
            {{ objectInfo.linkManTel }}
          </a-descriptions-item>
          <a-descriptions-item label="证件号码">
            {{ objectInfo.credentialsNo }}
          </a-descriptions-item>
          <a-descriptions-item label="支付周期">
            {{ objectInfo.RentPayName }}
          </a-descriptions-item>
          <a-descriptions-item label="租户类型">
            {{ objectInfo.disposalMethodName }}
          </a-descriptions-item>
          <a-descriptions-item label="附属建筑和资产">
            {{ objectInfo.associatedAssets }}
          </a-descriptions-item>
          <a-descriptions-item label="合同月租金(元)">
            {{ objectInfo.rent }}
          </a-descriptions-item>
          <a-descriptions-item label="押金">
            {{ objectInfo.rentalDeposit }}
          </a-descriptions-item>
          <a-descriptions-item label="合同面积">
            {{ objectInfo.area }}
          </a-descriptions-item>
          <a-descriptions-item label="每平方米/元/年">
            {{ objectInfo.unitAmount }}
          </a-descriptions-item>
          <a-descriptions-item label="联系地址">
            {{ objectInfo.address }}
          </a-descriptions-item>
          <a-descriptions-item label="备注">
            {{ objectInfo.remark }}
          </a-descriptions-item>
          <a-descriptions-item label="租赁日期">
            {{`${objectInfo.startTime}～${objectInfo.endTime}`}}
          </a-descriptions-item>
          <a-descriptions-item label="签名">
            <img :src="getImg(objectInfo.signUrl)" class="logo" alt="logo">
          </a-descriptions-item>
        </a-descriptions>
      </div>
    </a-spin>
    <photo-modal ref="photomodal"></photo-modal>
    <user-radio @save="handleRoomids" ref="userRadio" />
  </a-modal>
</template>

<script>
import Vue from "vue";
import { ACCESS_TOKEN } from "@/store/mutation-types";
import { mapActions, mapGetters } from "vuex";
import PhotoModal from "@/views/photoModal";
import userRadio from "./userRadio.vue";
import moment from "moment";

// import { getImg } from "@/api/students";

import { getDicDropList } from "@/api/dict";
import { getUnitPriceList } from "@/api/allApi";

export default {
  components: { PhotoModal, userRadio },
  props: {
    actionType: {
      type: String,
      required: false,
      default: "add",
    },

  },
  data () {
    return {
      a: null,
      action: "add",
      headers: {

        authorization: "authorization-text",

      },
      roomIds: [],
      roomNames: [],
      formItemLayout1: {
        labelCol: {
          xs: { span: 8 },
          sm: { span: 8 }
        },
        wrapperCol: {
          xs: { span: 16 },
          sm: { span: 16 }
        }
      },
      formItemLayout2: {
        labelCol: {
          xs: { span: 4 },
          sm: { span: 4 }
        },
        wrapperCol: {
          xs: { span: 20 },
          sm: { span: 20 }
        }
      },
      rentPayList: [{
        value: 1,
        label: '按月'
      }, {
        value: 2,
        label: '按季'
      },
      {
        value: 3,
        label: '半年'
      },
      {
        value: 4,
        label: '整年'
      }],
      tenantTypeList: [],
      PhotoUrlDb: {},
      PhotoUrl: '',
      PhotoUrlDbString: '',
      Photoloading: false,
      disposalList: [],
      credentialsTypeList: [],
      fileList: [],
      imageUrlDb: {},
      imageUrl: '',
      imageUrlDbString: '',
      fileImageList: [],
      currentId: null,
      CodeDisabled: false,
      required: false,
      indicator: <a-icon type="loading" style="font-size: 24px" spin />,
      form: this.$form.createForm(this),
      button_loading: false,
      spinning: true,
      tip: "加载中...",
      title: "查看",
      visible: false,
      objectInfo: {},
    };
  },
  async created () {

    getDicDropList({ CategoryId: 2086 }).then((res) => {
      this.credentialsTypeList = res.data.map((el) => {
        return { value: el.ID, label: el.Title };
      });
    });
    getDicDropList({ CategoryId: 2087 }).then((res) => {
      this.disposalList = res.data.map((el) => {
        return { value: el.ID, label: el.Title };
      });
    });
    getUnitPriceList().then((res) => {
      console.log(res)
      this.tenantTypeList = res.data.map((el) => {
        return { value: el.id, label: el.unitPriceName };
      });
    });

  },
  mounted () { },

  watch: {},
  computed: {},
  methods: {
    moment,
    view (data) {
      if (data) {
        Object.assign(this, {
          spinning: false,
          visible: true,

          currentId: data.id,
        });
        if (this.actionType == "view") {
          this.title = "查看"
        } else if (this.actionType == 'edit') {
          this.title = "编辑"
        } else {
          this.title = "添加"
        }

        this.initData(data);
      } else {
        this.spinning = false
        this.visible = true;
        this.form.resetFields();
        this.roomIds = []
        this.roomNames = []
        this.currentId = null;
        this.fileList = [];
      }
    },
    close () {
      this.form.resetFields();
      this.roomIds = []
      this.roomNames = []
      this.visible = false;
    },

    initData (data) {
      this.fileList = []
      setTimeout(() => {
        if (this.actionType == 'view') {
          this.objectInfo = data;

        } else {
          console.log(data)
          let room = data.RoomNames.split(",")
          this.roomIds = data.RoomIDs
          this.roomNames = data.RoomIDs.map((el, index) => {
            return {
              id: el,
              name: room[index]
            }
          })
          this.form.setFieldsValue({
            linkMan: data.linkMan,
            linkManTel: data.linkManTel,
            credentialsType: data.credentialsType,
            credentialsNo: data.credentialsNo,
            disposalMethod_: data.disposalMethod_,
            rent: data.rent,
            rentalDeposit: data.rentalDeposit,
            area: data.area,
            address: data.address,
            rentPay: data.rentPay,
            isSignContract: data.isSignContract ? 1 : 0,
            tenantType: data.tenantType,
            associatedAssets: data.associatedAssets,
            unitAmount: data.unitAmount,
            remark: data.remark,
            date: [
              this.$moment(data.startTime),
              this.$moment(data.endTime),
            ],
          });
        }

      }, 500);



    },

    handleChoose () {
      this.$refs.userRadio.view();

    },

    handleRoomids (rows) {
      console.log(3333, rows)
      // this.roomIds = rows.map(el => { return el.id })
      let rooms = rows.map(el => {
        return {
          id: el.id,
          name: `${el.BuildingName}${el.roomName}`,
        }
      })
      this.roomNames = this.roomNames.concat(rooms).reduce((acc, item) => {
        if (!acc.some(i => i.id === item.id)) {
          acc.push(item);
        }
        return acc;
      }, []);
      console.log(this.roomNames)

      this.$refs.userRadio.closeModal();

    },


    CloseRoom (index) {
      console.log(111112222, this.roomNames)
      this.roomNames.splice(index, 1);
    },
    handlePreview (file) {
      let str = this.getImg(file);
      this.$refs.photomodal.view(str);
    },

    handleSubmit () {
      let _this = this;
      if (!this.roomNames || this.roomNames.length == 0) {
        this.$message.error(`选择关联房间`)
        return
      }
      _this.form.validateFields((err, values) => {
        if (!err) {
          let params = {
            ...values,
            id: _this.currentId,
            isSignContract: values.isSignContract == 1 ? true : false,
            RoomIDs: _this.roomNames.map(el => { return el.id }),
            startTime: values.date ? _this.$moment(values.date[0]).format('YYYY-MM-DD HH:mm:ss') : '',
            endTime: values.date ? _this.$moment(values.date[1]).format('YYYY-MM-DD HH:mm:ss') : '',
          };
          _this.$emit("save", { ...params });
        }
      });
    },


    handleChange ({ file, fileList }) {
      console.log(222222, fileList)
      this.fileList = fileList;
      if (file.status === 'error') {
        this.$message.error(`认证过期:${file.response}`)
      }
      if (file.status === 'uploading') {
        this.Photoloading = true
        return
      }
      if (file.status === 'done') {
        this.PhotoUrlDb = file.response
        this.Photoloading = false
      }

    },

    handleImageChange ({ file, fileList }) {
      this.fileImageList = fileList;
      if (file.status === "error") {
        this.$message.error(`认证过期:${file.response}`);
      }

      if (file.status === "uploading") {
        this.Photoloading = true;
        return;
      }
      if (file.status === "done") {
        this.imageUrlDb = this.getImg(
          `${file.response.Path}/${file.response.NewFileName}`
        );

        this.signUrl = `${file.response.Path}/${file.response.NewFileName}`
        this.imageUrlDbString = `${file.response.Path}/${file.response.NewFileName}`;
        this.Photoloading = false;
      }

      // console.log(11122222,fileList)
    },
    beforePhotoUpload (file) {
      const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token;
      this.headers = {
        authorization: "Bearer " + token,
      };
      this.a =
        process.env.VUE_APP_API_BASE_URL +
        `/api/Upload/uploadImg?tablename=Consulting&signname=Attachment`;
      const isJpgOrPng =
        file.type === "image/jpeg" || file.type === "image/png";
      if (!isJpgOrPng) {
        this.$message.error("您只能上传JPG或PNG!");
      }
      const isLt2M = file.size / 1024 / 1024 < 2;
      if (!isLt2M) {
        this.$message.error("必须小于2MB!");
      }
      return isJpgOrPng && isLt2M;
    },

    beforeUpload (file) {
      const token = Vue.ls.get(ACCESS_TOKEN) && Vue.ls.get(ACCESS_TOKEN).token;
      this.headers = {
        authorization: "Bearer " + token,
      };
      this.a =
        process.env.VUE_APP_API_BASE_URL +
        `/api/Upload/UploadAnnex?tablename=Contract&signname=Annex`;
      let fileType = file.name.replace(/.+\./, "")
      const isJpgOrPng = fileType === 'doc' || fileType === 'docx' || fileType === 'pdf'

      if (!isJpgOrPng) {
        this.$message.error('您只能上传doc,docx,pdf文件!')
      }
      const isLt2M = file.size / 1024 / 1024 < 10;
      if (!isLt2M) {
        this.$message.error("必须小于10MB!");
      }
      return isLt2M;
    },

    getImg (str) {
      const url = `${process.env.VUE_APP_API_BASE_URL}${str}`;
      return url;
    },
    viewPhoto (data) {
      this.$refs.photomodal.view(data);
    },
  },
};
</script>
<style lang="less" scoped>
.img-preview {
  width: 150px;
  height: 150px;
}
.spin-content {
  padding: 20px;
}

.disable {
  pointer-events: none;
}
</style>
